package completion

import (
	"io"

	"gitee.com/youkelike/ziam/zctl/options"
	"gitee.com/youkelike/ziam/zctl/util/templates"
	"github.com/spf13/cobra"
)

const defaultBoilerPlate = ` 
# Use of this source code is governed by a MIT style    
# license that can be found in the LICENSE file.
`

var (
	completionLong = templates.LongDesc(`
		Output shell completion code for the specified shell (bash or zsh).
		The shell code must be evaluated to provide interactive
		completion of zctl commands.  This can be done by sourcing it from
		the .bash_profile.

		Detailed instructions on how to do this are available here:
		http://github.com/ziam/ziam/docs/installation/zctl.md#enabling-shell-autocompletion

		Note for zsh users: [1] zsh completions are only supported in versions of zsh >= 5.2`)

	completionExample = templates.Examples(`
		# Installing bash completion on macOS using homebrew
		## If running Bash 3.2 included with macOS
		    brew install bash-completion
		## or, if running Bash 4.1+
		    brew install bash-completion@2
		## If zctl is installed via homebrew, this should start working immediately.
		## If you've installed via other means, you may need add the completion to your completion directory
		    zctl completion bash > $(brew --prefix)/etc/bash_completion.d/zctl


		# Installing bash completion on Linux
		## If bash-completion is not installed on Linux, please install the 'bash-completion' package
		## via your distribution's package manager.
		## Load the zctl completion code for bash into the current shell
		    source <(zctl completion bash)
		## Write bash completion code to a file and source if from .bash_profile
		    zctl completion bash > ~/.iam/completion.bash.inc
		    printf "
		      # IAM shell completion
		      source '$HOME/.iam/completion.bash.inc'
		      " >> $HOME/.bash_profile
		    source $HOME/.bash_profile

		# Load the zctl completion code for zsh[1] into the current shell
		    source <(zctl completion zsh)
		# Set the zctl completion code for zsh[1] to autoload on startup
		    zctl completion zsh > "${fpath[1]}/_zctl"`)
)

var completionShells = map[string]func(out io.Writer, boilerPlate string, cmd *cobra.Command) error{
	"bash": runCompletionBash,
	// "zsh":  runCompletionZsh,
}

func NewCmdCompletion(out io.Writer, boilerPlate string) *cobra.Command {
	shells := []string{}
	for s := range completionShells {
		shells = append(shells, s)
	}

	cmd := &cobra.Command{
		Use:                   "completion SHELL",
		DisableFlagsInUseLine: true,
		Short:                 "Output shell completion code for the specified shell (bash or zsh)",
		Long:                  completionLong,
		Example:               completionExample,
		Run: func(cmd *cobra.Command, args []string) {
			err := RunCompletion(out, boilerPlate, cmd, args)
			options.CheckErr(err)
		},
		ValidArgs: shells,
	}

	return cmd
}

// RunCompletion checks given arguments and executes command.
func RunCompletion(out io.Writer, boilerPlate string, cmd *cobra.Command, args []string) error {
	if len(args) == 0 {
		return options.UsageErrorf(cmd, "Shell not specified.")
	}

	if len(args) > 1 {
		return options.UsageErrorf(cmd, "Too many arguments. Expected only the shell type.")
	}

	run, found := completionShells[args[0]]
	if !found {
		return options.UsageErrorf(cmd, "Unsupported shell type %q.", args[0])
	}

	return run(out, boilerPlate, cmd.Parent())
}

func runCompletionBash(out io.Writer, boilerPlate string, zctl *cobra.Command) error {
	if len(boilerPlate) == 0 {
		boilerPlate = defaultBoilerPlate
	}

	if _, err := out.Write([]byte(boilerPlate)); err != nil {
		return err
	}

	return zctl.GenBashCompletion(out)
}
